import { defineConfig, loadEnv, ProxyOptions } from "vite"
import uni from "@dcloudio/vite-plugin-uni"
import { resolve } from "path"

const pathResolve = (dir: string): any => {
	return resolve(__dirname, ".", dir)
}

export default defineConfig(({ command, mode }) => {
	// 根据当前工作目录中的 `mode` 加载 .env 文件
	// 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
	const env = loadEnv(mode, process.cwd(), "")
	const alias: Record<string, string> = {
		"/@": pathResolve("./src/"),
		assets: pathResolve("./src/assets")
	}
	let proxy: Record<string, string | ProxyOptions> = {}
	if (env.VITE_PROXY_URL) {
		proxy = {
			"/": {
				target: env.VITE_PROXY_URL,
				changeOrigin: true
			}
		}
	}
	return {
		// vite 配置
		plugins: [uni()],
		resolve: { alias },
		server: {
			host: "0.0.0.0",
			port: 1818,
			open: env.VITE_OPEN,
			proxy: proxy
		},
		define: {
			__APP_ENV__: JSON.stringify(env.APP_ENV)
		}
	}
})
